<?php
/**
 * 导航模型
 * 
 * @version $Id: Nav.php 269 2012-04-14 09:55:06Z linsir123 $
 */
class modelNav
{
	/**
	 * 导航数据
	 */
	public $navs;
	
	/**
	 * 平铺开的数据
	 */
	public $data;
	
	/**
	 * 构造函数
	 * // 数据结构为[id,pid,title,pinyin]
	 */
	public function __construct()
	{
		$this->navs = App::O('_nav.top');
		if ( ! is_array($this->navs)) 
			$this->navs = array();
			
		///
		$file = CACHE_DIR.'nav.php';
		if (file_exists($file)) 
			$data = require($file);
		else {
			App::V('pinyin');
			
			///
			$data = array();
			foreach ($this->navs as $id => $nav) 
				$data[$id] = array('id'=>$id, 'pid'=>0, 'title'=>$nav['title'], 'pinyin'=>string2pinyin($nav['title']));
				
			///
			$content = "<?php \r\n return ".var_export($data, true).';';
			file_put_contents($file, $content);
		}
		
		$this->data = $data;
	}
	
	/**
	 * 返回导航数据
	 */
	public function getAll()
	{
		return $this->navs;
	}
	
	/**
	 * 返回二级导航数据
	 */
	public function getSub($pCid)
	{
		$data = isset($this->navs[$pCid]) ? 
			$this->navs[$pCid]['sub'] : array();
			
		///
		if (empty($data)) {
			$data = array();
			$tmp = M::topRequest()->itemcatsGet(null, $pCid);
			$this->_join($tmp);
			foreach ($tmp as $var) 
				$data[$var['id']] = $var['title'];
		}
		
		return $data;
	}
	
	/**
	 * 根据传入的ID取得分类名称
	 */
	public function getOne($cId, $pinyin = "")
	{
		$data = isset($this->data[$cId]) ? 
			$this->data[$cId] : false;
			
		///
		if (empty($data)) {
			$tmp = M::topRequest()->itemcatsGet($cId);
			$this->_join($tmp);
			if ( ! empty($tmp)) 
				$data = $tmp[0];
		}
		
		///
		if ($data && $pinyin) 
			return $data['pinyin'] == $pinyin ? $data : false;
			
		return $data;
	}
	
	/**
	 * 根据传入的ID取得分类名称
	 */
	public function getLocation($cId)
	{
		$location = "";
		$nav = $this->getOne($cId);
		if ($nav) {
			if ($nav['pid']) 
				$location .= $this->getLocation($nav['pid']);
				
			///
			$href = AppView::urlClass(array('cid'=>$nav['id']));
			$location .= ' <a href="'.$href.'">'.$nav['title'].'</a> &gt;';
		}
		
		return $location;
	}
	
	/**
	 * 合并数据
	 */
	private function _join($data)
	{
		foreach ($data as $var) 
			$this->data[$var['id']] = $var;
	}
}
